<template>
  <div class="app-container">
    <h2 style="text-align: center">发布软笔资源包</h2>

    <el-steps
      :active="4"
      process-status="wait"
      align-center
      style="margin-bottom: 40px"
    >
      <el-step title="添加软笔出版社信息" />
      <el-step title="添加软笔书信息" />
      <el-step title="添加章节信息" />
      <el-step title="添加字体信息" />
      <el-step title="添加欣赏信息" />
      <el-step title="添加认读信息" />
      <el-step title="添加观察信息" />
      <el-step title="添加分析信息" />
      <el-step title="添加笔法信息" />
    </el-steps>
    <div>
      <el-form
        :inline="true"
        :model="dataForm"
        @keyup.enter.native="getWordByChapterId()"
      >
        <el-form-item>
          <el-cascader
            v-model="dataForm.cid"
            :options="chapterList"
            :props="{ expandTrigger: 'hover', value: 'id', label: 'name' }"
            @change="handleChange"
            placeholder="请选择章节"
          ></el-cascader>
        </el-form-item>
        <el-form-item>
          <el-button @click="getWordByChapterId()">查询</el-button>
          <el-button type="primary" @click="addWord(0)">新增</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-table
      :data="wordList"
      stripe
      v-loading="dataListLoading"
      style="width: 100%"
    >
      <el-table-column
        prop="wordId"
        header-align="center"
        align="center"
        label="字体id"
      ></el-table-column>
      <el-table-column
        prop="name"
        header-align="center"
        align="center"
        label="章节名称"
      ></el-table-column>
      <el-table-column
        prop="wordOrder"
        header-align="center"
        align="center"
        label="章节顺序"
      ></el-table-column>
      <el-table-column header-align="center" align="center" label="章节图片">
        <template slot-scope="scope">
          <el-image
            style="width: 100px; height: 100px"
            :src="scope.row.chapterPics[0]"
            :preview-src-list="scope.row.chapterPics"
          >
          </el-image>
        </template>
      </el-table-column>
      <el-table-column header-align="center" align="center" label="操作">
        <template slot-scope="scope">
          <el-button
            type="text"
            size="small"
            @click="addWord(1, scope.row.wordId)"
            >修改</el-button
          >
          <el-button
            type="text"
            size="small"
            @click="deleteById(scope.row.wordId)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper"
    ></el-pagination>
    <el-dialog
      :visible.sync="dialogWordVisible"
      :title="type == 0 ? '添加字体信息' : '修改字体信息'"
    >
      <el-form
        :rules="dataRule"
        ref="wordForm"
        :model="word"
        label-width="120px"
      >
        <el-form-item label="章节">
          <el-cascader
            v-model="dataForm.cid"
            :options="chapterList"
            :props="{ expandTrigger: 'hover', value: 'id', label: 'name' }"
            @change="handleChange"
            placeholder="请选择章节"
          ></el-cascader>
        </el-form-item>

        <el-form-item label="顺序" prop="wordOrder">
          <el-input-number
            v-model="word.wordOrder"
            controls-position="right"
            :min="1"
          ></el-input-number>
        </el-form-item>
        <el-form-item v-if="type == 0" label="视频" prop="chapterPics">
          <el-upload
            class="upload-demo"
            drag
            :action="'http://47.97.70.173/api/oss/upload'"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
            <div class="el-upload__tip" slot="tip">
              只能上传jpg/png文件，且不超过500kb
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="视频解析" prop="name">
          <el-input v-model="word.name" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogWordVisible = false">取 消</el-button>
        <el-button
          :disabled="saveWordBtnDisabled"
          type="primary"
          @click="saveOrUpdate"
          >确 定</el-button
        >
      </div>
    </el-dialog>

    <div>
      <el-button @click="previous">上一步</el-button>
      <el-button :disabled="saveBtnDisabled" type="primary" @click="next"
        >下一步</el-button
      >
    </div>
  </div>
</template>

<script>
import Vue from "vue";
export default {
  data() {
    return {
      saveBtnDisabled: false, // 下一步按钮是否禁用
      editionId: null,
      word: {
        // 章节对象
        name: "",
        wordOrder: null,
        id: null,
      },
      importHeaders: { wordId: 1 },
      dataForm: { cid: null }, // 用于查询
      wordList: [], // 字体集合
      chapterList: [], // 章节集合
      dataListLoading: false, // 加载章节数据
      uploadLoading: false, // 上传按钮是否处于加载中
      pageIndex: 1, // 当前页
      pageSize: 10, // 每页数据显示几条
      totalPage: 0, // 总记录数
      srcList: [], // 章节图片集合
      type: 0, // 0:添加1:修改
      dialogWordVisible: false, // 添加章节信息对话框
      saveWordBtnDisabled: false, // 章节信息保存按钮是否禁用
      dataRule: {
        // 数据规则
        name: [{ required: true, message: "名称不能为空", trigger: "blur" }],
        wordOrder: [
          { required: true, message: "顺序不能为空", trigger: "blur" },
        ],
        chapterPics: [
          { required: true, message: "请上传图片", trigger: "blur" },
        ],
      },
    };
  },

  created() {
    this.editionId = this.$route.params.id;
    // 获取章节集合
    this.getchapterListByEditionId();
  },

  methods: {
    handleChange(value) {
      //this.dataForm.cid =
    },
    // 获取章节分页数据
    getWordByChapterId() {
      this.dataListLoading = true;
      this.$http({
        url: this.$http.adornUrl(`/sf/cbchapter/list`),
        method: "get",
        params: this.$http.adornParams({
          page: this.pageIndex,
          limit: this.pageSize,
          chapterId: this.dataForm.cid[1],
        }),
      }).then(({ data }) => {
        if (data && data.code === 0) {
          console.log(data);
          this.wordList = data.chapterPage.records;
          this.totalPage = data.total;
        } else {
          this.wordList = [];
          this.totalPage = 0;
        }
        this.dataListLoading = false;
      });
    },
    // 通过editionId获取对应章节的集合
    getchapterListByEditionId() {
      this.$http({
        url: this.$http.adornUrl(
          `/sf/cbtypeface/getBookAndChapterByEditionId/${this.editionId}`
        ),
        method: "get",
      }).then(({ data }) => {
        if (data && data.code === 0) {
          console.log(data);
          this.chapterList = data.chapterList;
          this.dataForm.cid = [
            this.chapterList[0].id,
            this.chapterList[0].children[0].id,
          ];
          // 回显数据
          this.getWordByChapterId();
        } else {
          this.chapterList = [];
        }
      });
    },
    // 视频上传
    submitUpload() {
      this.uploadLoading = true;
      this.uploadLoading = false;
    },
    // 对话框中的保存或修改
    saveOrUpdate() {
      if (this.type == 0) {
        // 添加章节
        this.wordFormSubmit();
      } else {
        // 修改章节
        this.updateChapter();
      }
    },
    // 打开对话框，添加、修改
    addWord(status, id) {
      // 重置表单 应该只是把表单有的清空而已
      this.$nextTick(() => {
        this.$refs.wordForm.resetFields(); // this.$refs['wordForm'].resetFields(); 可能不识别 、还是不识别
      });
      if (status == 0) {
        // 添加
        this.type = 0;
        // 清空
        this.word.name = "";
        this.word.id = null;
        this.srcList = [];
      } else {
        // 修改
        this.type = 1;
        // 回显数据
        this.$http({
          url: this.$http.adornUrl("/sf/cbtypeface/info/" + id),
          method: "get",
        }).then(({ data }) => {
          this.word.id = data.cbChapter.id;
          this.word.name = data.cbChapter.name;
          this.word.wordOrder = data.cbChapter.corder;
          // this.dataForm.cid = data.cbChapter.bid;
        });
      }
      this.dialogWordVisible = true;
    },
    // 通过章节id删除章节
    deleteById(id) {
      this.$confirm(`确定对[字体id=${id}]进行[删除]操作?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$http({
            url: this.$http.adornUrl("/sf/cbtypeface/delete"),
            method: "post",
            data: this.$http.adornData([id], false),
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "删除成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.getWordByChapterId();
                },
              });
            } else {
              this.$message.error(data.msg);
            }
          });
        })
        .catch(() => {});
    },
    // 表单提交
    wordFormSubmit() {
      if (this.srcList != null && this.srcList.length > 0) {
        // 表单验证,只需要验证章节名称
        this.$refs["wordForm"].validateField("name", (valid) => {
          if (!valid) {
            console.log(this.srcList);
            this.$http({
              url: this.$http.adornUrl(`/sf/cbchapter/save`),
              method: "post",
              data: this.$http.adornData(
                {
                  bookId: this.dataForm.cid,
                  name: this.word.name,
                  wordOrder: this.word.wordOrder,
                  chapterPics: this.srcList,
                },
                false
              ),
            }).then(({ data }) => {
              if (data && data.code === 0) {
                this.$message({
                  message: "添加成功",
                  type: "success",
                  duration: 1500,
                  onClose: () => {
                    this.getWordByChapterId();
                    this.dialogWordVisible = false;
                  },
                });
              } else {
                this.$message.error(data.msg);
              }
            });
          }
        });
      } else {
        // 表单验证
        this.$refs["wordForm"].validate((valid) => {
          if (valid) {
            console.log(this.srcList);
            this.$http({
              url: this.$http.adornUrl(`/sf/cbtypeface/save`),
              method: "post",
              data: this.$http.adornData(
                {
                  bookId: this.dataForm.cid,
                  name: this.word.name,
                  wordOrder: this.word.wordOrder,
                  chapterPics: this.srcList,
                },
                false
              ),
            }).then(({ data }) => {
              if (data && data.code === 0) {
                this.$message({
                  message: "添加成功",
                  type: "success",
                  duration: 1500,
                  onClose: () => {
                    this.getWordByChapterId();
                    this.dialogWordVisible = false;
                  },
                });
              } else {
                this.$message.error(data.msg);
              }
            });
          }
        });
      }
    },
    updateChapter() {
      // 表单验证,只需要验证章节名称
      this.$refs["wordForm"].validateField("name", (valid) => {
        if (!valid) {
          this.$http({
            url: this.$http.adornUrl(`/sf/cbtypeface/update`),
            method: "post",
            data: this.$http.adornData(
              {
                id: this.word.id,
                name: this.word.name,
                corder: this.word.wordOrder,
                bid: this.dataForm.cid,
              },
              false
            ),
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "修改成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.getWordByChapterId();
                  this.dialogWordVisible = false;
                },
              });
            } else {
              this.$message.error(data.msg);
            }
          });
        }
      });
    },
    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val;
      this.pageIndex = 1;
      this.getWordByChapterId();
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageIndex = val;
      this.getWordByChapterId();
    },
    // 上一步
    previous() {
      console.log("previous");
      this.$router.push({
        path: "/ruanbi/ruanbiBookAdd/" + this.$route.params.id,
      }); // editionId
    },
    // 下一步
    next() {
      this.$router.push({ path: "/ruanbi/ruanbiChapterAdd" });
      // 记录到哪一步了和id
      this.$cookie.set("path", "ruanbiChapterAdd");
      this.$cookie.set("id", this.$route.params.id);
    },
  },
};
</script>
<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
